﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BoYuanCore.CoreCodeTemplates.DBMappingRules;
using BoYuanCore.CoreCodeTemplates.FineUICore;


namespace BoYuanCore.CoreCodeTemplates.FineUICore.Template
{
    public class ListPagecshtmlTemplate : FineUIBase
    {
        public static string GetCode(TableModel tb)
        {
            List<DbColumnInfo> list = tb.Columns;
            DbColumnInfo keyModel = list.FirstOrDefault(p => p.IsPrimaryKey == true);
            if (keyModel == null) { throw new Exception("表没有主键，没办法生成代码！ControllerTemplate"); }

            string code = string.Format(@"
@{{
    ViewBag.Title = ""列表"";
    var F = Html.F();
}}

@section head {{

}}

@section body {{
    @(F.Panel().ID(""Panel1"").BodyPadding(3).ShowBorder(false).ShowHeader(false).Layout(LayoutType.Fit).AutoScroll(true).IsViewPort(true)
        .Toolbars(F.Toolbar().Position(ToolbarPosition.Top).Items(
                F.Button().ID(""BtnAdd"").Icon(Icon.Add).Text(""新增"").OnClientClick(""openWindow()""),
                F.ToolbarSeparator(),
                F.Button().ID(""BtnDelete"").Icon(Icon.Delete).Text(""批量删除"").OnClientClick(""DeleteRows()""))
            )
            .Items(
                F.Grid().Layout(LayoutType.Fit).AllowPaging(true).IsDatabasePaging(true).EnableCheckBoxSelect(true).CheckBoxSelectOnly(true).ShowHeader(false).ShowBorder(true)
                .ID(""Grid1"").Listener(""paging"", ""onGridBind"").DataIDField(""{2}"").EnableTextSelection(true).EnableHeaderMenu(false)
                .Toolbars(F.Toolbar().Position(ToolbarPosition.Top)
                    .Items(
                        F.TextBox().ID(""txb_keyword"").EmptyText(""关键词查询""),
                        F.Button().ID(""BtnSearch"").Text(""查询"").Icon(Icon.SystemSearch).OnClientClick(""onGridBind()"")
                    )
            )
            .PageItems(
                F.ToolbarSeparator(),
                F.DropDownList().ID(""ddlPageSize"").Width(160).Label(""每页记录数"")
                    .Items(
                        F.ListItem().Text(""10"").Value(""10""),
                        F.ListItem().Text(""20"").Value(""20"").Selected(true),
                        F.ListItem().Text(""50"").Value(""50""),
                        F.ListItem().Text(""100"").Value(""100"")
                    ),
                F.ToolbarSeparator()
            )
            .Columns(
                //F.RowNumberField(),
                F.RenderField().HeaderText(""编辑"").ColumnID(""Actions"").Width(50).RendererFunction(""renderActions"")
{0}
            )
    ))
    @(F.Window().ID(""Window1"").Height(500).Width(700).IsModal(true).EnableMaximize(true).EnableIFrame(true).Hidden(true).Icon(Icon.ApplicationFormEdit).Target(Target.Top).EnableResize(true)
        .CloseAction(CloseAction.HidePostBack).Listener(""close"", ""onGridBind""))
}}

@section script {{
    <script>
        function onGridBind(event, pageindex,oldPageIndex) {{
            var grid1 = F.ui.Grid1;
            if (!pageindex) pageindex=0;
            grid1.setPageIndex(pageindex);
            // 触发后台事件
            F.doPostBack('@Url.Action(""ShowGrid"")', ""Panel1"");
        }}

        F.ready(function() {{
            @if(ViewBag.InitLoadJs != null)
            {{
                @Html.Raw(ViewBag.InitLoadJs)
            }}
            onGridBind();
            F.ui.ddlPageSize.on('change', function () {{ onGridBind() }});

            var grid = F.ui.Grid1;
            grid.el.on('click', 'a.action', function (event) {{
                var cnode = $(this);
                var rowEl = cnode.closest('.f-grid-row');
                var rowData = grid.getRowData(rowEl);
                var rowId = rowData.id;

                if (cnode.hasClass('editit')) {{
                    openWindow(rowId); // 编辑窗体
                }}
            }});
        }})

        function DeleteRows() {{
            var result = '', grid = F.ui.Grid1;
            var selectRows = grid.getSelectedRows(true);
            if (selectRows.length == 0) {{
                NotifyQuestion(""请选择要删除的选中行"");
                return;
            }}
            F.confirm({{
                message: ""确定要执行选中行删除操作吗？"",
                ok: function() {{                   
                    $.each(selectRows,
                        function(index, item) {{
                            result += ',' + item.id; // item.id对应绑定的.DataIDField(""GridID"")的值;item.values.字段1 对应列DataField(""字段1"")
                        }});
                    F.doPostBack('@Url.Action(""BtnDelete_Click"")', {{ ids: result }});                    
                }}
            }})
        }}

        function openWindow(id) {{
            var url = '@Url.Action(""Add"", ""{1}"")';
            if (id) {{
                F.ui.Window1.show(url+'?id='+id, '编辑');
            }} else {{
                F.ui.Window1.show(url, '新增');
            }}
        }}
    </script>
}}
", GetGridColumnStr(tb.Columns) //0
                , tb.TableNameToClassName  //1
                , (!keyModel.IsIdentity && keyModel.PropertyName == "long") ? "GridID" : keyModel.DbColumnNameToClassName //2 非自增long类型主键为雪花ID(默认GridID显示)
            );

            return code;
        }

        private static string GetGridColumnStr(List<DbColumnInfo> cms)
        {
            StringBuilder sb = new StringBuilder();
            var list = cms.Where(p => p.IsPrimaryKey == false).ToList();
            for (int i = 0; i < list.Count; i++)
            {
                switch (list[i].PropertyName)
                {
                    case "bool":
                        sb.AppendLine(string.Format("                ,F.RenderCheckField().HeaderText(\"{1}\").DataField(\"{0}\").RenderAsStaticField(true).Width(100)"
                            , list[i].DbColumnNameToClassName, GetComment(list[i].Coment, list[i].DbColumnNameToClassName)));
                        break;

                    case "datetime":
                        sb.AppendLine(string.Format("                ,F.RenderField().HeaderText(\"{1}\").DataField(\"{0}\").FieldType(FieldType.Date).Renderer(Renderer.Date).RendererArgument(\"yyyy-MM-dd\").Width(100)"
                            , list[i].DbColumnNameToClassName, GetComment(list[i].Coment, list[i].DbColumnNameToClassName)));
                        break;
                    //长类型
                    case "ulong"://break;
                    case "uint"://break;
                    case "long"://break;
                    case "byte"://break;
                    case "sbyte"://break;
                    case "short"://break;
                    case "ushort"://break;
                    case "enum": //break;
                    case "int":
                        //数字应该为右对齐
                        sb.AppendLine(string.Format("                ,F.RenderField().HeaderText(\"{1}\").DataField(\"{0}\").FieldType(FieldType.Int).TextAlign(TextAlign.Right).Width(100)"
                            , list[i].DbColumnNameToClassName, GetComment(list[i].Coment, list[i].DbColumnNameToClassName)));
                        break;

                    case "decimal"://break;
                    case "double":
                        //数字应该为右对齐
                        sb.AppendLine(string.Format("                ,F.RenderField().HeaderText(\"{1}\").DataField(\"{0}\").FieldType(FieldType.Double).TextAlign(TextAlign.Right).Width(100)"
                            , list[i].DbColumnNameToClassName, GetComment(list[i].Coment, list[i].DbColumnNameToClassName)));
                        break;

                    case "float":
                        //数字应该为右对齐
                        sb.AppendLine(string.Format("                ,F.RenderField().HeaderText(\"{1}\").DataField(\"{0}\").FieldType(FieldType.Float).TextAlign(TextAlign.Right).Width(100)"
                            , list[i].DbColumnNameToClassName, GetComment(list[i].Coment, list[i].DbColumnNameToClassName)));
                        break;
                    //case "guid": //break;
                    default:
                        sb.AppendLine(string.Format("                ,F.RenderField().HeaderText(\"{1}\").DataField(\"{0}\").Width(100)"
                            , list[i].DbColumnNameToClassName, GetComment(list[i].Coment, list[i].DbColumnNameToClassName)));
                        break;
                }
            }

            return sb.ToString();
            //return "                " + (sb.ToString().TrimStart().TrimStart(','));
        }
    }
}
